package controller

import (
	"errors"
	"github.com/e421083458/gorm"
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/util/gconv"
	"rock/customer/dto"
	"rock/customer/initParam"
	"rock/customer/middleware"
)

// @Summary 通讯录列表
// @Description 传参只需要传UserId，Search
// @Tags 通讯录
// @ID   /addrbooklist
// @Accept  json
// @Produce  json
// @Param polygon body dto.User true "body"
// @Success 200 {object} middleware.Response{} "success"
// @Router /addrbooklist [post]
func (c *AddrBookController) addrBookList(router *gin.Context) {
	params := &dto.User{}
	if err := params.BindingParams(router); err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}
	// 如果传groupid，则意味着查询出的结果不包含该群的成员
	exceptMember := make([]string, 0)
	if params.GroupId != "" {
		// 查询群对应的群成员
		groupMember, err := groupService.GroupMember(router, BusinessDB, params.GroupId)
		if err != nil {
			dealRequestError(router, err)
			return
		}
		for _, v := range groupMember {
			exceptMember = append(exceptMember, gconv.String(v.UserID))
		}
	}
	// 查询客服权限
	csUser, err := customerServiceService.CsUser(router, InstanceDB, gconv.Int(params.UserId))
	if err != nil {
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
			return
		}
	}
	// 查询客服所在群组
	csUserGroup, err := customerServiceService.CsUserGroup(router, BusinessDB, params.UserId)
	if err != nil {
		dealRequestError(router, err)
		return
	}
	csGroupStr := ""
	for _, v := range csUserGroup {
		csGroupStr = csGroupStr + gconv.String(v.GroupId) + ","
	}
	if csGroupStr != "" {
		csGroupStr = csGroupStr[0 : len(csGroupStr)-1]
	}
	//查询当前客服所能查看技能组及其成员
	redisData, err := addrBookList(router, params, csUser, csGroupStr, exceptMember)
	if err != nil {
		if err.Error() == initParam.DataIsNotExist {
			responseData := dto.NullComeBack{
				Page: dto.Page{
					PageNum:  params.PageNum,
					PageSize: params.PageSize,
					Total:    0,
				},
				List: make([]string, 0),
			}
			middleware.ResponseSuccess(router, responseData)
			return
		}
		middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
		return
	}
	responseData := redisData
	middleware.ResponseSuccess(router, responseData)

}
